import axios from 'axios'

const request = axios.create({
  baseURL: 'http://localhost:1337/api',
  timeout: 60000
})

request.interceptors.request.use(
  (config) => {
    // Do something before request is sent
    if (config.url === '/auth/local') return config

    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }

    return config
  },
  (error) => {
    // Do something with request error
    return Promise.reject(error)
  }
)

request.interceptors.response.use(
  (response) => {
    // Do something with response data

    if (response.status === 200) {
      // Do something with success response data
      return response.data
    } else {
      // Do something with error response data
    }

    return response
  },
  (error) => {
    // Do something with response error
    return Promise.reject(error)
  }
)

export default request
